import { createApp, type App, type Component } from 'vue';

// Toast 组件
const ToastComponent: Component = {
  props: {
    message: String,
    type: {
      type: String,
      default: 'info' // info, success, error, warning
    },
    duration: {
      type: Number,
      default: 3000
    }
  },
  template: `
    <div class="toast" :class="'toast-' + type">
      <div class="toast-message">{{ message }}</div>
    </div>
  `,
  mounted() {
    setTimeout(() => {
      this.$el.remove();
    }, this.duration);
  }
};

let toastContainer: HTMLElement | null = null;

function ensureToastContainer() {
  if (!toastContainer) {
    toastContainer = document.createElement('div');
    toastContainer.id = 'toast-container';
    toastContainer.className = 'toast-container';
    document.body.appendChild(toastContainer);
    
    // 添加样式
    const styleElement = document.createElement('style');
    styleElement.innerHTML = `
      .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        display: flex;
        flex-direction: column;
        gap: 10px;
      }
      
      .toast {
        padding: 12px 20px;
        border-radius: 4px;
        color: white;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        animation: fadeIn 0.3s ease-out;
        max-width: 300px;
      }
      
      .toast-info {
        background-color: #1890ff;
      }
      
      .toast-success {
        background-color: #52c41a;
      }
      
      .toast-error {
        background-color: #f5222d;
      }
      
      .toast-warning {
        background-color: #faad14;
      }
      
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
      }
    `;
    document.head.appendChild(styleElement);
  }
  return toastContainer;
}

export function showToast(
  message: string,
  options: {
    type?: 'info' | 'success' | 'error' | 'warning';
    duration?: number;
  } = {}
) {
  const container = ensureToastContainer();
  const toastElement = document.createElement('div');
  container.appendChild(toastElement);
  
  const app = createApp(ToastComponent, {
    message,
    type: options.type || 'info',
    duration: options.duration || 3000
  });
  
  app.mount(toastElement);
  
  // 返回一个关闭函数
  return () => {
    app.unmount();
    toastElement.remove();
  };
}

// 快捷方法
export const toast = {
  info: (msg: string, duration?: number) => showToast(msg, { type: 'info', duration }),
  success: (msg: string, duration?: number) => showToast(msg, { type: 'success', duration }),
  error: (msg: string, duration?: number) => showToast(msg, { type: 'error', duration }),
  warning: (msg: string, duration?: number) => showToast(msg, { type: 'warning', duration })
};